import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

public class ServerSocketHandler implements Runnable {
    private Socket socket = null;

    public ServerSocketHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {

        String line = null;
        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
        ) {
            line = reader.readLine();
            System.out.println("server recv :" + line);
            String rsp = "err order.";
            if (line.equals("query time order.")) {
                rsp = String.format("rsp %s from server.", new Date());
            }
            writer.println(rsp);

            for (line = reader.readLine(); Global.whileFlag && line != null && !line.trim().equals(""); line = reader.readLine()) {
                System.out.println("server recv :" + line);
                if (line.equals("query time order.")) {
                    rsp = String.format("rsp %s from server.", new Date());
                } else {
                    rsp = "err order.";
                }
                writer.println(rsp);
            }
            System.out.println("recv client close link req...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("time server link closing.");
            if (socket != null) {
                System.out.println("time server link closed.");
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("close time server link err.");
                }
                socket = null;
            }
        }
    }
}
